﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Web;
using System.Web.Profile;
using System.ComponentModel;
using System.Configuration;

namespace N2.BlogEngine.Providers
{
	using global::BlogEngine.Core.Providers;
	using be = global::BlogEngine.Core;

	public partial class N2BlogProvider: BlogProvider
	{
		public override be.AuthorProfile SelectProfile(string id)
		{
			return ProfileBase.Create(id).AsBlogEngine();
		}

		public override void InsertProfile(be.AuthorProfile profile)
		{
			this.UpdateProfile(profile);
		}

		public override void UpdateProfile(be.AuthorProfile profile)
		{
			var _profile = ProfileBase.Create(profile.Id);
			
			(
				from _prop in TypeDescriptor.GetProperties(typeof(be.AuthorProfile))
					.Cast<PropertyDescriptor>()
				join _profileProperty in ProfileBase.Properties.Cast<SettingsProperty>()
					on _prop.Name.ToUpper() equals _profileProperty.Name.ToUpper()
				where !_prop.IsReadOnly
				select _prop
			)
				.ToList()
				.ForEach(_p => _profile[_p.Name] = _p.GetValue(profile));

			_profile.Save();
		}

		public override void DeleteProfile(be.AuthorProfile profile)
		{
			ProfileManager.DeleteProfile(profile.Id);
		}

		public override List<be.AuthorProfile> FillProfiles()
		{
			return
				ProfileManager.GetAllProfiles(ProfileAuthenticationOption.Authenticated)
					.Cast<ProfileInfo>()
					.Select(_pi => ProfileBase.Create(_pi.UserName).AsBlogEngine())
					.ToList();
		}
	}
}
